<template>
	<view class="page">
		<view class="">
			<view class="device-name">{{data.aname}}</view>
			<view class="device-status">
				<view class="">
					<text>运行状态</text>
					<text :style="{'color': data.color}">（{{data.status}}）</text>
				</view>
				<view class="device-status__icon" :style="{'background-color': data.color}"></view>
			</view>
		</view>
		<view class="device-info">
			<view class="device-info__head">概览信息</view>
			<view class="device-info__list" v-for="item in list" :key="item.CnlCode">
				<view class="device-info__list--left">{{item.name}}</view>
				<view class="device-info__list--right">
					<text>{{item.value}}</text>
					<text style="margin-left: 10rpx;">{{item.unit}}</text>
				</view>
			</view>
			<view class="device-info__more">
				<view class="" style="color: #aaa;" @click="goMorePage">更多</view>
				<view class="" style="margin-left: 10rpx;" @click="goMorePage">
					<u-icon name="arrow-right" color="#aaa" size="15"></u-icon>
				</view>
			</view>
		</view>
		<view class="device-chart">
			<view class="device-chart__head">曲线</view>
			<view class="date-tabs">
				<u-tabs class="" :activeStyle="{color: 'orange'}" lineColor="orange" :list="dateMenuList"
					@change="dateMenuChange"></u-tabs>
			</view>
			<view class=""
				style="display: flex;justify-content: space-between;padding: 20rpx 60rpx;box-sizing: border-box;border-bottom: 1rpx solid #eee;">
				<view class="">
					<view class="arrow" @click="prev">
						<view class="arrow-left"></view>
					</view>
				</view>
				<view class="" @click="selectDateTime">{{dateType}}</view>
				<view class="">
					<view class="arrow" @click="next">
						<view class="arrow-right"></view>
					</view>
				</view>
			</view>
			<view class="" style="border-bottom: 1rpx solid #eee;" v-show="type == 0">
				<u-tabs class="" :itemStyle="{'font-size': '27rpx','height': '80rpx'}" :activeStyle="{color: 'orange'}" lineColor="orange" :list="subMenuList"
					@change="subMenuChange"></u-tabs>
			</view>
			<view class="" style="margin: 20rpx 10rpx;">
				<text>{{textType}}发电量：</text>
				<text>{{dkWH}}</text>
				<text style="margin-left: 10rpx;">度</text>
			</view>
			<view class="" style="height: 500rpx;padding-bottom: 20rpx;">
				<chart :options="option" />
			</view>
		</view>
		
		<u-datetime-picker :show="dayPickerVisible" v-model="day" mode="date" @cancel="dayPickerVisible = false"
			@confirm="dayConfirm" />
		<u-datetime-picker :show="monthPickerVisible" v-model="month" mode="year-month"
			@cancel="monthPickerVisible = false" @confirm="monthConfirm" />
		<u-picker :show="yearPickerVisible" :defaultIndex="defaultIndex" :columns="yearColumns"
			@cancel="yearPickerVisible = false" @confirm="yearConfirm"></u-picker>
	</view>
</template>

<script>
	import _custom from '@/common/_custom.js'
	import {
		getTableSuffix,
		setDotNumber
	} from '@/common/custom_util.js'
	import Chart from '@/components/custom/chart/echart.vue'
	import moment from 'moment'
	
	
	let colors = ['#fbb034','#00a4e4','#0abf53','#ff4c4c','#ffdd00','#8db9ca'];
	export default {
		components: {
			Chart
		},
		data() {
			return {
				data: {},
				list: [
					{
						name: '日发电量',
						value: '',
						unit: 'kWh'
					},
					{
						name: '总有功功率',
						value: '',
						unit: 'kW'
					},
					{
						name: '总发电量',
						value: '',
						unit: 'MWh'
					},
					{
						name: '总直流功率',
						value: '',
						unit: 'kW'
					},
				],
				more: [],
				dateMenuList: [{
						name: '日'
					},
					{
						name: '月'
					},
					{
						name: '年'
					},
				],
				subMenuList: [
					{
						name: '功率'
					},
					{
						name: '交流电流'
					},
					{
						name: '交流电压'
					},
				],
				dkWH: '',
				option: {},
				day: moment().format('YYYY-MM-DD'),
				month: moment().format('YYYY-MM'),
				year: moment().format('YYYY'),
				type: 0,//日：0，月：1，年：2
				dayType: 0,//功率：0，交流：1
				dayPickerVisible: false,
				monthPickerVisible: false,
				yearPickerVisible: false,
				yearColumns: [
					[]
				],
				defaultIndex: [],
			}
		},
		onLoad(options) {
			let sYear = 2000;
			let eYear = moment().format('YYYY');
			for (let i = sYear; i <= eYear; i++) {
				this.yearColumns[0].push(i)
			}
			this.defaultIndex.push(this.yearColumns[0].length - 1)
			this.data = JSON.parse(options.data);
			this.getDeviceCnlList();
			this.getDayKWList();
		},
		computed: {
			textType() {
				let t = ''
				switch (this.type) {
					case 0:
						t = '当日';
						break;
					case 1:
						t = '当月';
						break;
					case 2:
						t = '当年';
						break;
					case 3:
						t = '总';
						break;
				}
				return t
			},
			dateType() {
				switch (this.type) {
					case 0:
						return moment(this.day).format('YYYY-MM-DD')
						break;
					case 1:
						return moment(this.month).format('YYYY-MM')
						break;
					case 2:
						return this.year
						break;
					case 3:
						break;
				}
			}
		},
		methods: {
			/**
			 * 用设备台账接口获取设备里的点位信息
			 */
			getDeviceCnlList() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getDeviceCnlList',
					apiparam: {
						tablesuffix: getTableSuffix(),
						devicecode: this.data.aname,
					},
					success(res) {
						res.forEach(item => {
							that.list.forEach(v => {
								if(item.Name == v.name) {
									v.value = setDotNumber(item.Val,3)
									v.unit = item.Unit
								}
							})
						})
						that.more = res;
					}
				})
			},
			/**
			 * 获取日的所有功率数据
			 */
			getDayKWList() {
				Promise.all([this.getSunnyCnlDayKWList('DKW','总直流功率'),this.getSunnyCnlDayKWList('TKW','总有功功率')]).then(res =>{
					this.setDayChart(res)
				}).catch(() => {
					this.option = {}
				})
			},
			/**
			 * 获取日的所有交流电流数据
			 */
			getDayExchangeIList() {
				Promise.all([this.getSunnyCnlDayKWList('IA','A相电流'),this.getSunnyCnlDayKWList('IB','B相电流'),this.getSunnyCnlDayKWList('IC','C相电流')]).then(res =>{
					this.setDayChart(res)
				}).catch(() => {
					this.option = {}
				})
			},
			/**
			 * 获取日的所有交流电压数据
			 */
			getDayExchangeUList() {
				Promise.all([this.getSunnyCnlDayKWList('UA','A相电压'),this.getSunnyCnlDayKWList('UB','B相电压'),this.getSunnyCnlDayKWList('UC','C相电压')]).then(res =>{
					this.setDayChart(res)
				}).catch(() => {
					this.option = {}
				})
			},
			/**
			 * 获取某日发电量分时累计数据(KWH)
			 */
			getSunnyCnlDayKWList(v,n) {
				let that = this;
				return new Promise((resolve,reject) =>{
					_custom.getDataJava({
						apiname: 'getSunnyCnlDayKWList',
						apiparam: {
							tablesuffix: getTableSuffix(moment(this.day).format('YYYY'), moment(this.day).format('MM')),
							obsdate: this.day,
							cnlcode: this.data.aname + v
						},
						success(res) {
							if(res.length) {
								res.forEach(item => {
									item.name = n
								})
								resolve(res)
							} else {
								reject()
							}
						},
						fail() {
							reject()
						}
					})
				})
			},
			/**
			 * 获取某月光伏点位日数据
			 */
			getSunnyCnlMonthKWHList() {
				let that = this;
				this.dkWH = '/';
				_custom.getDataJava({
					apiname: 'getSunnyCnlMonthKWHList',
					apiparam: {
						tablesuffix: getTableSuffix(moment(this.month).format('YYYY'), moment(this.month).format(
							'MM')),
						obsdate: moment(this.month).format('YYYY-MM'),
						devicecode: this.data.aname
					},
					success(res) {
						if (res.length) {
							let daysNumber = moment(this.month).daysInMonth();
							let days = [];
							let data = [];
							for (let i = 1; i <= daysNumber; i++) {
								days.push(i);
								let flag = false
								res.forEach(item => {
									let day = moment(item.DateTime).format('DD')
									if (day == i) {
										data.push([i-1, (item.DKWH * 1).toFixed(2)])
										flag = true;
									}
								})
								if (!flag) {
									data.push([i, 0])
								}
							}
							let wh = 0;
							res.forEach(item => {
								wh += (item.DKWH * 1)
							})
							that.dkWH = wh.toFixed(1);
							that.option = {
								legend: {
									left: '2%',
									bottom: '0',
									icon: "circle",
									itemWidth: 10,
									itemHeight: 10,
									textStyle: {
										color: '#333',
										fontSize: 14,
									},
									data: [
										{
											name: '发电量'
										}
									]
								},
								tooltip: {
									trigger: 'axis',
								},
								grid: {
									top: '11%',
									left: '10%',
									bottom: '25%'
								},
								dataZoom: { // 放大和缩放
									type: 'inside'
								},
								xAxis: [{
									type: 'category',
									boundaryGap: true,
									axisTick: {
										show: false,
									},
									splitLine: {
										show: false,
									},
									axisLine: {
										show: true,
										lineStyle: {
											color: '#666'
										},
									},
									data: days
								}],
								yAxis: {
									type: 'value',
									name: 'kWh',
									nameTextStyle: {
										color: '#666',
										padding: [0, 0, 0, 0],
									},
									axisLine: {
										show: true,
										lineStyle: {
											color: '#666'
										},
									},
								},
								series: [{
									name: '发电量',
									data: data,
									type: 'bar',
									areaStyle: {},
									itemStyle: {
										color: 'orange'
									},
									symbol: 'none',
									label: {
										show: false,
									},
								}]
							}
						} else {
							that.option = {}
						}
					},
					fail() {
						that.option = {}
					}
				})
			},
			/**
			 * 获取某年光伏点位月数据
			 */
			getSunnyCnlYearKWHList() {
				let that = this;
				this.dkWH = '/';
				_custom.getDataJava({
					apiname: 'getSunnyCnlYearKWHList',
					apiparam: {
						year: this.year,
						devicecode: this.data.aname
					},
					success(res) {
						if (res.length) {
							let label = [];
							let data = res.map(item => {
								let month = moment(item.DateTime).format('MM')
								label.push(month)
								return [month, (item.Val * 1).toFixed(1)]
							})
							that.option = {
								legend: {
									left: '2%',
									bottom: '0',
									icon: "circle",
									itemWidth: 10,
									itemHeight: 10,
									textStyle: {
										color: '#333',
										fontSize: 14,
									},
									data: [
										{
											name: '发电量'
										}
									]
								},
								tooltip: {
									trigger: 'axis',
								},
								grid: {
									top: '11%',
									left: '13%',
									bottom: '25%'
								},
								dataZoom: { // 放大和缩放
									type: 'inside'
								},
								xAxis: [{
									type: 'category',
									boundaryGap: true,
									axisTick: {
										show: false,
									},
									splitLine: {
										show: false,
									},
									axisLine: {
										show: true,
										lineStyle: {
											color: '#666'
										},
									},
									data: label
								}],
								yAxis: {
									type: 'value',
									name: 'kWh',
									nameTextStyle: {
										color: '#666',
										padding: [0, 0, 0, 0],
									},
									axisLine: {
										show: true,
										lineStyle: {
											color: '#666'
										},
									},
								},
								series: [{
									name: '发电量',
									data: data,
									type: 'bar',
									areaStyle: {},
									itemStyle: {
										color: 'orange'
									},
									symbol: 'none',
									label: {
										show: false,
									},
								}]
							}
							let wh = 0;
							res.forEach(item => {
								wh += (item.Val * 1)
							})
							that.dkWH = wh.toFixed(1);
						} else {
							that.option = {}
						}
					},
					fail() {
						that.option = {}
					}
				})
			},
			/**
			 * 处理日的不同参数数据
			 */
			setDayChart(v) {
				let flag = 0
				v.forEach(item => {
					if(!item.length) flag += 1
				})
				if(flag == v.length) {
					this.dkWH = '/'
					return
				}
				let data = [];
				let legends = [];
				v.forEach(item => {
					legends.push({
						name: item.length ? item[0].name : ''
					})
					data.push(item.map(value => {
						return [moment(value.DateTime).format('x') * 1, (value.Val * 1).toFixed(2)]
					}))
				})
				this.dkWH = v[0].length ? (v[0][0].DKWH * 1).toFixed(1) : '';
				let name = '';
				switch(this.dayType) {
					case 0:
						name = '功率（kW）'
						break;
					case 1:
						name = '电流（A）'
						break;
					case 2:
						name = '电压（U）'
						break;
				}
				let series = []
				data.forEach((item,index) => {
					series.push({
						name: legends[index].name,
						data: item,
						type: 'line',
						itemStyle: {
							normal: {
								width: 1,
								color: colors[index],
							},
						},
						symbol: 'none',
						label: {
							show: false,
						},
					})
				})
				let option = {
					animation: false,
					legend: {
						left: '2%',
						bottom: '0',
						icon: "circle",
						itemWidth: 10,
						itemHeight: 10,
						textStyle: {
							color: '#333',
							fontSize: 14,
						},
						data: legends
					},
					dataZoom: { // 放大和缩放
						type: 'inside'
					},
					tooltip: {
						trigger: 'axis'
					},
					grid: {
						top: '11%',
						bottom: '25%',
						right: '10%'
					},
					xAxis: [{
						type: 'time',
						min: moment(this.day).format('YYYY-MM-DD') + ' 00:00',
						max: moment(this.day).format('YYYY-MM-DD') + ' 23:59',
						minInterval: 24,
						boundaryGap: false,
						axisTick: {
							show: false,
						},
						axisLabel: {
							format: 'xLabelFormat'
						},
						splitLine: {
							show: false,
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: '#666'
							},
						},
					}],
					yAxis: {
						type: 'value',
						name: name,
						nameTextStyle: {
							color: '#666',
							padding: [0, 0, 0, 0],
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: '#666'
							},
						},
					},
					series: series
				}
				this.option = option;
			},
			/**
			 * 跳转更多页面
			 */
			goMorePage() {
				uni.navigateTo({
					url: '/pages/home/child/sunny-power/more?data=' + JSON.stringify(this.more)
				})
			},
			/**
			 * 切换功率/交流电流/交流电压
			 */
			subMenuChange(e) {
				this.dayType = e.index;
				this.changeDayType();
			},
			changeDayType() {
				switch(this.dayType) {
					case 0:
						this.getDayKWList();
						break;
					case 1:
						this.getDayExchangeIList();
						break;
					case 2:
						this.getDayExchangeUList();
						break;
				}
			},
			/**
			 * 切换年月日总
			 * @param {Object} e
			 */
			dateMenuChange(e) {
				switch (e.index) {
					case 0:
						this.type = 0;
						this.changeDayType();
						break;
					case 1:
						this.type = 1;
						this.getSunnyCnlMonthKWHList();
						break;
					case 2:
						this.type = 2;
						this.getSunnyCnlYearKWHList();
						break;
					case 3:
						this.type = 3;
						break;
				}
			},
			/**
			 * 前一天/月/年
			 */
			prev() {
				switch (this.type) {
					case 0:
						this.day = moment(this.day).subtract(1, 'day').format('YYYY-MM-DD');
						this.changeDayType();
						break;
					case 1:
						this.month = moment(this.month).subtract(1, 'month').format('YYYY-MM');
						this.getSunnyCnlMonthKWHList();
						break;
					case 2:
						this.year = moment(this.year).subtract(1, 'year').format('YYYY');
						this.getSunnyCnlYearKWHList();
						break;
					case 3:
						break;
				}
			},
			/**
			 * 后一天/月/年
			 */
			next() {
				switch (this.type) {
					case 0:
						this.day = moment(this.day).subtract(-1, 'day').format('YYYY-MM-DD');
						this.changeDayType();
						break;
					case 1:
						this.month = moment(this.month).subtract(-1, 'month').format('YYYY-MM');
						this.getSunnyCnlMonthKWHList();
						break;
					case 2:
						this.year = moment(this.year + '').subtract(-1, 'year').format('YYYY');
						this.getSunnyCnlYearKWHList();
						break;
					case 3:
						break;
				}
			},
			/**
			 * 点击日期
			 */
			selectDateTime() {
				switch (this.type) {
					case 0:
						this.dayPickerVisible = true
						break;
					case 1:
						this.monthPickerVisible = true
						break;
					case 2:
						this.yearPickerVisible = true;
						break;
					case 3:
						break;
				}
			},
			/**
			 * 日选择器确认
			 */
			dayConfirm(e) {
				this.day = moment(e.value).format('YYYY-MM-DD');
				this.changeDayType();
				this.dayPickerVisible = false;
			},
			/**
			 * 月选择器确认
			 */
			monthConfirm(e) {
				this.month = moment(e.value).format('YYYY-MM');
				this.getSunnyCnlMonthKWHList();
				this.monthPickerVisible = false;
			},
			/**
			 * 年选择器确认
			 */
			yearConfirm(e) {
				this.year = e.value[0];
				this.getSunnyCnlYearKWHList();
				this.yearPickerVisible = false;
			},
		}
	}
</script>

<style scoped lang="scss">
	.device-name {
		font-size: 35rpx;
		font-weight: bold;
		background-color: #fff;
		padding: 10rpx 20rpx;
	}
	
	.device-status {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background-color: #fff;
		
		&__icon {
			width: 25rpx;
			height: 25rpx;
			border-radius: 50%;
			margin-left: 30rpx;
		}
	}
	
	.device-info {
		background-color: #fff;
		margin-top: 20rpx;
		padding: 20rpx 40rpx;
		
		&__head {
			font-size: 34rpx;
			margin-bottom: 10rpx;
		}
		
		&__list {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;
		}
		
		&__more {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100rpx;
		}
	}
	
	.device-chart {
		background-color: #fff;
		margin-top: 20rpx;
		
		&__head {
			padding: 20rpx;
		}
	}
	
	.arrow {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, .1);
		position: relative;
		overflow: hidden;
	
		&-left {
			width: 15rpx;
			height: 15rpx;
			border-left: 1rpx solid #000;
			border-bottom: 1rpx solid #000;
			transform: rotate(45deg) translate(-50%, -50%);
			position: absolute;
			left: 40%;
			top: 55%;
		}
	
		&-right {
			width: 15rpx;
			height: 15rpx;
			border-right: 1rpx solid #000;
			border-top: 1rpx solid #000;
			transform: rotate(45deg) translate(-50%, -50%);
			position: absolute;
			right: 40%;
			top: 55%;
		}
	}
	
	.date-tabs /deep/ .u-tabs__wrapper__nav__item {
		flex: 1;
	}
</style>
